package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureMediaScannerConnection;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.FileDocAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.FileListBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;

public class SearchFileActivity extends MyBaseActivity {

    @BindView(R.id.edit_search)
    ContainsEmojiEditText editSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.recycler2)
    RecyclerView recycler2;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.empty_layout)
    EmptyDataLayout emptyLayout;
    private FileDocAdapter fileDocAdapter;
    private String savePath = PathUtils.getExternalDownloadsPath();
    private List<FileListBean.PageBean.ListBean> DataBeanFileDoc = new ArrayList<>();
    private String docUrl;
    private String docName;
    private boolean isLoadMore = true;
    private int PAGE_SIZE = 10;
    private int currentPage = 1;
    private String keyword;
    private String parentId;
    private String filePath;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_file;
    }

    @Override
    protected void initView() {
        setModuleTitle("文件搜索");
    }

    @Override
    protected void initData() {
        parentId = getIntent().getStringExtra("parentId");
        //文件
        LinearLayoutManager manager2 = new LinearLayoutManager(context);
        recycler2.setLayoutManager(manager2);
        recycler2.addItemDecoration(new SpacesItemDecoration(0, 0, 0, ItemDecorationSpaces, ItemDecorationSpaces));

        fileDocAdapter = new FileDocAdapter(context, DataBeanFileDoc);
        recycler2.setAdapter(fileDocAdapter);
        fileDocAdapter.setOnItemClickListener(new FileDocAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                FileListBean.PageBean.ListBean listBean = DataBeanFileDoc.get(position);
                itemClickDoc(listBean);
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    keyword = UIUtils.getTextView(textView);
                    if (StringUtils.isEmpty(keyword)) {
                        ToastUtils.showLong("请输入关键字~");
                        return true;
                    }
                    getFileList(1);
                    return true;
                }
                return false;
            }
        });
    }

    private void itemClickDoc(FileListBean.PageBean.ListBean listBean) {
        docUrl = listBean.getUrl();
        docName = listBean.getName();
        filePath = savePath + "/" + docName;

        if (StringUtils.isEmpty(docName)) {
            ToastUtils.showLong("文件读取错误！");
            return;
        }

        if (StringUtils.isEmpty(docUrl)) {
            ToastUtils.showLong("文件链接错误！");
            return;
        }

        boolean isHasVideo = PictureMimeType.isUrlHasVideo(docUrl);
        boolean isHasImage = PictureMimeType.isUrlHasImage(docUrl);

        if (isHasVideo) {
            Bundle bundle = new Bundle();
            bundle.putString("vodeoUrl", docUrl);
            bundle.putString("title", docName);
            IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), VideoPlayActivity.class, bundle);
            return;
        }

        if (isHasImage) {
            ArrayList<LocalMedia> pictureMediaList = new ArrayList<>();
            LocalMedia localMedia =  LocalMedia.generateHttpAsLocalMedia(docUrl);
            pictureMediaList.add(localMedia);
            BaseApplication.initPreviewModel().startActivityPreview(0, false, pictureMediaList);
            return;
        }


        XXPermissions.with(SearchFileActivity.this)
                .permission(Permission.WRITE_SETTINGS)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.WRITE_SETTINGS)) {
                            dealFile();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            ToastUtils.showLong("请手动授予修改系统设置权限");
                            XXPermissions.startPermissionActivity(SearchFileActivity.this, permissions);
                        } else {

                        }

                    }
                });
    }

    @Override
    protected void getData() {
        initListener();
    }


    @OnClick({R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                keyword = UIUtils.getEditText(editSearch);

                if (StringUtils.isEmpty(keyword)) {
                    ToastUtils.showLong("请输入关键字~");
                    return;
                }

                getFileList(1);
                break;
        }
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == XXPermissions.REQUEST_CODE) {
//            if (XXPermissions.isGranted(SearchFileActivity.this, Permission.WRITE_SETTINGS)) {
//                //如果文件存在
//                if (FileUtils.isFileExists(filePath)) {
//                    openFileReader(filePath);
//                } else {
//                    //文件不存在 ,下载完成之后打开
//                    downloadDocFile();
//                }
//            } else {
//                ToastUtils.showLong("修改系统设置权限获取失败！");
//            }
//        }
//
//
//    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getFileList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBeanFileDoc, PAGE_SIZE);
                    getFileList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    private void dealFile() {
        XXPermissions.with(SearchFileActivity.this)
                // 不适配 Android 11 可以这样写
                .permission(Permission.Group.STORAGE)
                // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) || permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
                            //如果文件存在
                            if (FileUtils.isFileExists(filePath)) {
                                openFileReader(filePath);
                            } else {
                                //文件不存在 ,下载完成之后打开
                                downloadDocFile();
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            new XPopup.Builder(SearchFileActivity.this)
                                    .isDestroyOnDismiss(true)
                                    .dismissOnTouchOutside(true)
                                    .hasShadowBg(true)
                                    .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    XXPermissions.startPermissionActivity(SearchFileActivity.this, permissions);
                                                }
                                            }, null, false)
                                    .show();
                        }
                    }
                });
    }

    /**
     * 获取文件
     */
    private void getFileList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("name", keyword);
        hashMap.put("typeId", parentId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_TYPE_SON)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            FileListBean fileListBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                fileListBean = new FileListBean();
                                fileListBean = gson.fromJson(result, FileListBean.class);
                                List<FileListBean.PageBean.ListBean> dataBeans = fileListBean.getPage().getList();

                                try {
                                    emptyLayout.setIsShowView(false);
                                    recycler2.setVisibility(View.VISIBLE);

                                    if (dataBeans != null) {

                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        if (!isLoadMore) {
                                            if (currentPage > 1) {
                                                ToastUtils.showLong(getResources().getString(R.string.text_no_more_data));
                                            } else {
                                                if (dataBeans.size() == 0) {
                                                    //显示占位图
                                                    emptyLayout.setIsShowView(true);
                                                    recycler2.setVisibility(View.GONE);
                                                }

                                            }
                                        }

                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            fileDocAdapter.clearData();
                                        }
                                        DataBeanFileDoc.addAll(dataBeans);
                                        fileDocAdapter.upData(DataBeanFileDoc);

                                    } else {
                                        if (currentPage == 1) {
                                            //显示占位图
                                            recycler2.setVisibility(View.GONE);
                                            emptyLayout.setIsShowView(true);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                emptyLayout.setIsShowView(true);
                                recycler2.setVisibility(View.GONE);
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    /**
     * 下载文件
     */
    private void downloadDocFile() {
        if (StringUtils.isEmpty(docUrl)) {
            ToastUtils.showLong("未获取到文件链接！");
            return;
        }

        GetRequest<File> request = OkGo.<File>get(docUrl);
        DownloadTask downloadTask = OkDownload.request(docUrl, request);
        downloadTask.folder(savePath);
        downloadTask.fileName(docName);
        downloadTask.register(new DownloadListener(docUrl) {
            @Override
            public void onStart(Progress progress) {
                showDownLoadDialog();
                //howLoadingDialog("下载中...");
            }

            @Override
            public void onProgress(Progress progress) {

            }

            @Override
            public void onError(Progress progress) {
                hideDownLoadDialog();
                ToastUtils.showLong(getResources().getString(R.string.text_download_fail));
            }

            @Override
            public void onFinish(File file, Progress progress) {
                //扫描更新媒体库
                hideDownLoadDialog();
//                MediaScannerConnection.scanFile(context, new String[]{savePath}, null, null);
                new PictureMediaScannerConnection(context, file.getAbsolutePath(), () -> {
                });
                ToastUtils.showLong(getResources().getString(R.string.text_download_success));

                openFileReader(filePath);
                docUrl = null;
                docName = null;

            }

            @Override
            public void onRemove(Progress progress) {

            }
        });
        downloadTask.save();
        downloadTask.start();
    }

    /**
     * 打开下载的文件
     */
    private void openFileReader(String filePath) {
        HashMap<String, String> params = new HashMap<>();
        params.put("local", "true");
        try {
            JSONObject Object = new JSONObject();
            Object.put("pkgName", getApplicationContext().getPackageName());
            params.put("menuData", Object.toString());
            QbSdk.getMiniQBVersion(SearchFileActivity.this);
            int ret = QbSdk.openFileReader(SearchFileActivity.this, filePath, params, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                    MyLogUtil.e("testest", "====**====" + s);

                }
            });
            //1：用QQ浏览器打开 2：用MiniQB打开 3：调起阅读器弹框 -1：filePath为空 打开失败 -5：高版本Android没有定义ContentProvider -6：打开apk类型的文件uri解析为空 -7：fileType为空
            switch (ret) {
                case -1:
                    ToastUtils.showLong("打开失败，文件地址有误!");
                    break;
                case -5:
                    ToastUtils.showLong("高版本Android没有定义ContentProvider!");
                    break;
                case -6:
                    ToastUtils.showLong("打开apk类型的文件uri解析为空!");
                    break;
                case -7:
                    ToastUtils.showLong("fileType为空!");
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}